/**
 * Title:UserRoleService<br>
 * Description:用户角色服务类<br>
 * Copyright © Xiamen Dripstill  NetWorks Co.,Ltd.
 * @Create:2018-07-03<br>
 * @author:Sun Yijing<br>
 * @version: Object v1.0.0<br>
 * <br>
 * 修改历史:<br>
 * 修改人		修改日期		修改描述<br>
 * -----------------------------------<br>
 * <br>
 * <br>
 */
package com.yoooya.base.service;

import java.io.File;
import java.io.IOException;

import javax.annotation.PostConstruct;

import org.apache.commons.io.FileUtils;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import com.qiniu.common.QiniuException;
import com.qiniu.common.Zone;
import com.qiniu.http.Response;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.UploadManager;
import com.qiniu.util.Auth;
import com.yoooya.base.utils.IdUtils;

@Service
@Transactional
public class UploadService {

	@Value("${image.server.domain}")
	private String imageServerDomain;
	@Value("${image.root.dir}")
	private String imageRootDir;
	@Value("${image.allow.format}")
	private String imageAllowedFormat;
	@Value("${image.max.size}")
	private Long imageMaxSize;
	@Value("${qiniu_access_key}")
	private String accessKey;
	@Value("${qiniu_secret_key}")
	private String secretKey;
	@Value("${qiniu_backet_name}")
	private String backetName;
	// 密钥配置
	private Auth auth = null;
	// 创建上传对象
	private UploadManager uploadManager = null;
	private Logger logger = LoggerFactory.getLogger(getClass());

	@PostConstruct
	private void init() {
		auth = Auth.create(accessKey, secretKey);
		Zone z = Zone.autoZone();
		Configuration c = new Configuration(z);
		uploadManager = new UploadManager(c);
	}

	/**
	 * 获取UpToken
	 * 
	 * @return
	 */
	public String getUpToken() {
		String upToken = auth.uploadToken(backetName);
		return upToken;
	}

	/**
	 * 上传文件
	 * 
	 * @param file
	 * @param fileName
	 * @return
	 */
	public String upload(File file, String fileName) {
		if (file == null) {
			return "";
		}
		try {
			uploadManager.put(file, fileName, auth.uploadToken(backetName));
			String url = StringUtils.join(new Object[] { imageServerDomain,
					fileName }, '/');
			return url;
		} catch (QiniuException e) {
			Response r = e.response;
			try {
				System.out.println(r.bodyString());
			} catch (QiniuException e1) {
				e1.printStackTrace();
			}
		}
		return "";
	}

	/**
	 * 上传文件
	 * 
	 * @param file
	 * @param fileName
	 * @return
	 */
	public String upload(MultipartFile file) {
		if (file == null) {
			return "";
		}
		if(file.getSize()==0){
			return "";
		}
		String originalName = file.getOriginalFilename();
		originalName = originalName.toLowerCase();
		String type = FilenameUtils.getExtension(originalName);
		String fileName = IdUtils.id() + "." + type;
		File path = FileUtils.getFile(imageRootDir, "file");
		try {
			FileUtils.forceMkdir(path);
			File ordinalFile = FileUtils.getFile(path, fileName);
			file.transferTo(ordinalFile);
			String url = upload(ordinalFile, fileName);
			ordinalFile.delete();
			return url;
		} catch (IOException e) {
			logger.error(e.getMessage(), e);
		}
		return "";
	}
}